using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using EnvDTE;

namespace DoxyComment
{
	public partial class OptionsProviderPage : UserControl, EnvDTE.IDTToolsOptionsPage
	{
		private Dictionary<IProviderInfo,ICommentProvider> providerObjs;

		public OptionsProviderPage()
		{
			InitializeComponent();

			// Create hash table for caching provider objects
			providerObjs = new Dictionary<IProviderInfo,ICommentProvider>();

			// Listen to changes on the comment provider drop down
			activeProviderDropList.SelectedValueChanged += new EventHandler(activeProviderDropList_SelectedValueChanged);

			// Set the property used for text in drop list
			activeProviderDropList.DisplayMember = "DisplayName";

			ConfigHelper cfg = ConfigHelper.Instance;

			// Add available comment providers to drop down
			foreach (IProviderInfo pi in cfg.ProviderTypes)
			{
				// TODO: Filter off providers with no options
				activeProviderDropList.Items.Add(pi);
			}
			activeProviderDropList.SelectedItem = cfg.ActiveProviderType;
		}

		void activeProviderDropList_SelectedValueChanged(object sender, EventArgs e)
		{
			// Create an instance of the selected provider and set it in the
			// property grid.
			ICommentProvider provider;
			IProviderInfo key = (IProviderInfo)activeProviderDropList.SelectedItem;
			if (providerObjs.ContainsKey(key))
			{
				provider = providerObjs[key];
			}
			else
			{
				// Not already created- create new.. .
				provider = ((IProviderInfo)key).CreateProviderInstance();
				providerObjs[key] = provider;
			}

			// Set active provider in property grid
			propertyGrid.SelectedObject = provider;
		}

		#region IDTToolsOptionsPage implementation

		public void GetProperties(ref object propertiesObject)
		{
			propertiesObject = null;
		}

		public void OnAfterCreated(EnvDTE.DTE DTEObject)
		{
			// TODO:  Add ProviderPage.OnAfterCreated implementation
		}

		public void OnCancel()
		{
			// TODO:  Add ProviderPage.OnCancel implementation
		}

		public void OnHelp()
		{
			// TODO:  Add ProviderPage.OnHelp implementation
		}

		public void OnOK()
		{
			// Write new provider properties back to registry
			foreach (KeyValuePair<IProviderInfo,ICommentProvider> pair in providerObjs)
			{
				pair.Key.SaveProviderProperties(pair.Value);
			}
		}

		#endregion
	}
}
